//
//  ViewController.swift
//  EagleEye
//
//  Created by Armstrong Liu on 2018/9/18.
//  Copyright © 2018 weirdstudio. All rights reserved.
//

import UIKit
import Foundation
import Alamofire

class MainVC: UIViewController {
    @IBOutlet var streamView: UIImageView!
    @IBOutlet var loadingView: UIActivityIndicatorView!
    @IBOutlet var hostField: UITextField!
    @IBOutlet var portField: UITextField!
    @IBOutlet var playBtn: UIButton!
    @IBOutlet var controlBg: UIView!
    @IBOutlet weak var leftBtn: UIButton!
    @IBOutlet weak var rightBtn: UIButton!
    @IBOutlet weak var upBtn: UIButton!
    @IBOutlet weak var downBtn: UIButton!
    @IBOutlet weak var fullScreenBtn: UIButton!
    
    var streamingController: MjpegStreamingController!
    var url: URL?
    var playing = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.initListener()
        self.configUI()
        
        streamingController = MjpegStreamingController(imageView: self.streamView)
        streamingController.didStartLoading = { [unowned self] in
            self.loadingView.startAnimating()
        }
        streamingController.didFinishLoading = { [unowned self] in
            self.loadingView.stopAnimating()
        }
        
        let userDefaults = UserDefaults.standard
        guard let hostStr:String = userDefaults.string(forKey: "host"), let portStr:String = userDefaults.string(forKey: "port") else {
            return
        }
        self.hostField.text = hostStr
        self.portField.text = portStr
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func configUI() {
        self.leftBtn.setImage(UIImage.init(family: "eaglemoon", code: "\u{ea44}", fontSize: 10.0, color: .white), for: UIControlState.normal)
        self.rightBtn.setImage(UIImage.init(family: "eaglemoon", code: "\u{ea42}", fontSize: 10.0, color: .white), for: UIControlState.normal)
        self.upBtn.setImage(UIImage.init(family: "eaglemoon", code: "\u{ea41}", fontSize: 10.0, color: .white), for: UIControlState.normal)
        self.downBtn.setImage(UIImage.init(family: "eaglemoon", code: "\u{ea43}", fontSize: 10.0, color: .white), for: UIControlState.normal)
    }
    
    func initListener() {
        NotificationCenter.default.addObserver(forName: Notification.Name.UIKeyboardWillShow, object: nil, queue: OperationQueue.main, using: showKeyboard)
        NotificationCenter.default.addObserver(forName: Notification.Name.UIKeyboardWillHide, object: nil, queue: OperationQueue.main, using: hideKeyboard)
    }
    
    @IBAction func leftBtnClick(_ sender: UIButton) {
        Alamofire.request("http://control.gymkers.cn:8088/?action=l").responseString { responseString in
        }
    }

    @IBAction func rightBtnClick(_ sender: UIButton) {
        Alamofire.request("http://control.gymkers.cn:8088/?action=r").responseString { responseString in
        }
    }
    
    @IBAction func upBtnClick(_ sender: UIButton) {
        Alamofire.request("http://control.gymkers.cn:8088/?action=u").responseString { responseString in
        }
    }
    
    @IBAction func downBtnClick(_ sender: UIButton) {
        Alamofire.request("http://control.gymkers.cn:8088/?action=d").responseString { responseString in
        }
    }
    
    @IBAction func centerBtnClick(_ sender: UIButton) {
        Alamofire.request("http://control.gymkers.cn:8088/?action=c").responseString { responseString in
        }
    }
    
    @IBAction func fullScreenBtnClick(_ sender: UIButton) {
    }
    
    @IBAction func play(_ sender: UIButton) {
        guard let hostStr = self.hostField.text, hostStr != "", let portStr = self.portField.text, portStr != "" else {
            // 提示
            print("aaaaaa")
            return
        }
        let userDefaults = UserDefaults.standard
        userDefaults.set(self.hostField.text, forKey: "host")
        userDefaults.set(self.portField.text, forKey: "port")
        
        url = URL(string: "http://\(hostStr):\(portStr)/?action=stream")
        streamingController.contentURL = url
        
        if playing {
            self.playBtn.setTitle("Play", for: .normal)
            streamingController.stop()
            playing = false
            self.controlBg.isHidden = true
        }
        else {
            streamingController.play()
            playing = true
            self.playBtn.setTitle("Stop", for: .normal)
        }
    }
    
    @IBAction func toggleControlView(_ sender: UITapGestureRecognizer) {
        if playing && self.controlBg.isHidden {
            self.controlBg.isHidden = false
        }
        else if playing && !self.controlBg.isHidden {
            self.controlBg.isHidden = true
        }
    }
    
    @IBAction func endEdit(_ sender: UITapGestureRecognizer) {
        self.playBtn.superview?.endEditing(true)
    }
    
    func showKeyboard(notification: Notification) {
        let keyboardY:CGFloat = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.origin.y
        let offsetY = keyboardY - UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.01) {
            self.playBtn.superview?.transform = CGAffineTransform(translationX: 0.0, y: offsetY)
        }
    }
    
    func hideKeyboard(notification: Notification) {
        UIView.animate(withDuration: 0.01) {
            self.playBtn.superview?.transform = CGAffineTransform(translationX: 0.0, y: 0.0)
        }
    }
}
